<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use think\Controller;
use think\Request;
use think\Lang;
use fast\Tree;
use fast\Cols;
use fast\Random;
use fast\Date;
use think\cache\Driver\File;

class Module extends Backend{
    //商户模型对象
    protected $model = null;
    //省份数据
    protected $provincedata = array();
    //类别数据
    protected $categorylist = array();
    protected $categorydata = array();
    protected $columnlist = array();

    public function _initialize(){
        parent::_initialize();
        $this->model = model('Module');
        $rr = array();
        $rr['id'] = '0';
        $rr['name'] = '请选择';
        $tree = Tree::instance();
        $tree->init(collection(model('Category')->where('pid','0')->order('weigh desc')->select())->toArray(), 'pid');
        //$this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $this->categorydata = $tree->getChild(0);
        $this->columnarry = Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/module.php','',1);
        //$this->view->assign('provincedata',json_encode($this->provincedata,JSON_UNESCAPED_UNICODE));
        //print_r(json_encode($this->categorylist));exit;
        $this->view->assign('categorydata',$this->categorylist);
    }
    public function add(){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params){
                $fc = new File();$menu = model('AuthRule');$menunid = 0;
                $this->modelValidate = false;
                if ($this->dataLimit){
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try{
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['itemid'] = str_replace('-','',Random::uuid());
                    $result = $this->model->allowField(true)->save($params);
                    //生成目录
                    if($params['dir']){
                        $dirc = ADMIN_PATH.DS.'controller'.DS.$params['dir'];
                        $dirv = ADMIN_PATH.DS.'view'.DS.$params['dir'];
                        $dirp = PUBLIC_PATH.DS.'assets'.DS.'js'.DS.'backend'.($params['dir']?DS.$params['dir']:'');
                        if(!is_dir($dirc)){
                            mkdir($dirc);
                        }
                        if(!is_dir($dirv)){
                            mkdir($dirv);
                        }
                        if(!is_dir($dirv.DS.$params['enname'])){
                            mkdir($dirv.DS.$params['enname']);
                        }
                        if(!is_dir($dirp)){
                            mkdir($dirp);
                        }
                    }else{
                        $dirv = ADMIN_PATH.DS.'view';
                        if(!is_dir($dirv.DS.$params['enname'])){
                            mkdir($dirv.DS.$params['enname']);
                        }
                    }
                    //写缓存
                    $lst = model('Module')->select();
                    $fc->set('module',$lst);
                    if(!$params['pid']){
                          //创建菜单
                          $marry = array();
                          $m = model('AuthRule')->getAuthRuleByName($params['dir']?$params['dir']:$params['enname']);
                          if($m){
                              $menunid = $m['itemid'];
                          }else{
                              $marry['itemid'] = str_replace('-','',Random::uuid());
                              $marry['pid'] = '';
                              $marry['name'] = $params['dir']?$params['dir']:$params['enname'];
                              $marry['title'] = $params['name'].'管理';
                              $marry['icon'] = 'fa fa-table';
                              $marry['ismenu'] = 1;
                              $marry['status'] = 'close';
                              $rr = $menu->data($marry,true)->isUpdate(false)->save();
                              $menunid = $menu->itemid;
                          }
                          $marry['itemid'] = str_replace('-','',Random::uuid());
                          $marry['pid'] = $menunid;
                          $marry['name'] = ($params['dir']?$params['dir'].'/':'').$params['enname'].'/index';
                          $marry['title'] = $params['name'].'列表';
                          $marry['icon'] = 'fa fa-circle-o';
                          $marry['ismenu'] = 1;
                          $marry['status'] = 'close';
                          $marry['weigh'] = 100;
                          model('AuthRule')->data($marry,true)->isUpdate(false)->save();
                          $marry['itemid'] = str_replace('-','',Random::uuid());
                          $marry['pid'] = $menunid;
                          $marry['name'] = ($params['dir']?$params['dir'].'/':'').$params['enname'].'/add';
                          $marry['title'] = '添加'.$params['name'];
                          $marry['icon'] = 'fa fa-circle-o';
                          $marry['ismenu'] = 1;
                          $marry['status'] = 'close';
                          $marry['weigh'] = 99;
                          model('AuthRule')->data($marry,true)->isUpdate(false)->save();
                          //如果有隶属关系，就不需要创建菜单了。
                    }
                    if ($result !== false){
                        $this->success();
                    }else{
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e){
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $this->view->assign("categorydata",$this->categorydata);
            $fc = new File();
            $parentList = $fc->get('module');
            if(!$parentList){
                $parentList = $this->model->select();
            }
            $this->view->assign('parentList',$parentList);
            return $this->view->fetch();
        }
    }
    public function edit($ids = NULL){
        $row = $this->model->with('category')->find($ids);$fc = new File();
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)){
            if (!in_array($row[$this->dataLimitField], $adminIds)){
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params){
                try{
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    //生成目录
                    if($params['dir']){
                        $dirc = ADMIN_PATH.DS.'controller'.DS.$params['dir'];
                        $dirv = ADMIN_PATH.DS.'view'.DS.$params['dir'];
                        $dirp = PUBLIC_PATH.DS.'assets'.DS.'js'.DS.'backend'.($params['dir']?DS.$params['dir']:'');
                        if(!is_dir($dirc)){
                            mkdir($dirc);
                        }
                        if(!is_dir($dirv)){
                            mkdir($dirv);
                        }
                        if(!is_dir($dirv.DS.$params['enname'])){
                            mkdir($dirv.DS.$params['enname']);
                        }
                        if(!is_dir($dirp)){
                            mkdir($dirp);
                        }
                    }else{
                        $dirv = ADMIN_PATH.DS.'view';
                        if(!is_dir($dirv.DS.$params['enname'])){
                            mkdir($dirv.DS.$params['enname']);
                        }
                    }
                    //生成缓存
                    $lst = model('Module')->select();
                    $fc->set('module',$lst);
                    if ($result !== false){
                        $this->success();
                    }
                    else{
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e){
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $lst = array();
        $ll = $fc->get('module');
        if(!$ll){
            $ll = model('Module')->select();
        }
        //print_r($row);exit;
        $this->view->assign("parentList",$ll);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    public function index(){
        $columnlist = Cols::columnread('module');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('pkey_name')){
            return $this->selectpage();
        }
        $searchfileds = array();
        $searchfileds['name'] = 'varcharmid';
        $searchfileds['enname'] = 'varcharmid';
        list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds);
        $order = 'desc';
        $sort = 'itemid';
        $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
        $totalpage = 1;$page = 1;
        if($limit>0){
            $totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
            //总页数
            if($offset>0){
                $page = intval($offset/$limit)+1;
            }
            //当前页
        }
        $list = $this->model
                ->with('category')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
        //print_r(json_encode($list));exit;
        $arealist = array();$citylist = array();
        for ($i = 0; $i < count($list); $i++) {
            $list[$i]['catname'] = $list[$i]['category']['name'];
            if(isset($list[$i]['createtime'])){
                $list[$i]['createdate'] = Date::timetodate($list[$i]['createtime'],3);
            }
            if(isset($list[$i]['updatetime'])){
                $list[$i]['updatedate'] = Date::timetodate($list[$i]['updatetime'],3);
            }
            unset($list[$i]['intro']);unset($list[$i]['content']);
        }
        $result = array("total" => $total, "rows" => $list);
        $this->view->assign("lists",$result['rows']);
        $this->view->assign("columnlist",$columnlist);
        $this->view->assign("total",$result['total']);
        $this->view->assign("offset",$offset);
        $this->view->assign("limit",$limit);
        $this->view->assign("totalpage",$totalpage);
        $this->view->assign("page",$page);
        return $this->view->fetch('index');
    }
    public function getindex(){
        return $this->view->fetch();
    }
    public function info(){
        //调用nusoap
        //初始化客户端对象，这个对象是类 soapclient 的一个实例，
        //把服务程序的 URL 地址传递给soapclient类的构造函数。
        $client = new soapclient( 'http://www.andiff.net/index/module/info.html');

        // 避免乱码
        $client->soap_defencoding = 'UTF-8' ;
        $client->decode_utf8 = false ;
        $client->xml_encoding = 'UTF-8' ;
        header("Content-Type:text/html;charset=utf-8;");

        // 参数转为数组形式传递
        $paras = array ( 'username' => 'Bruce Lee' );

        // 目标方法没有参数时，可省略后面的参数
        $result = $client->call( 'validate' , $paras );
        // 检查错误，获取返回值
        if (! $err = $client->getError()){
            echo " 返回结果： " .'<br/> result -- ' . $result ;
        }
        else{
            echo " 调用出错： " . $err ;
        }
    }
    public function getoption(){
        $fc = new File();
        $list = $fc->get('module');
        $ll = array();
        foreach ($list as $k => $v) {
            $ll[$v['itemid']] = $v['name'];
        }
        print_r(json_encode($ll));
        exit;
    }
    //编辑增加实体的模板生成
    public function makebjtemplate(){
        $this->model->makeaddtemplate($this->request->get('name'));
        $this->model->makeedittemplate($this->request->get('name'));
        echo '生成成功';exit;
    }
    //编辑列表实体的模板生成
    public function makelisttemplate(){
        $this->model->makelisttemplate($this->request->get('name'));
        echo '生成成功';exit;
    }
    //生成model.php文件
    public function makemodelphp(){
      $this->model->makemodelphp($this->request->get('name'));
      echo '生成成功';exit;
    }
    //生成js文件
    public function makejstemplate(){
      $this->model->makejstemplate($this->request->get('name'));
      echo '生成成功';exit;
    }
    //生成数据库表
    public function makesql(){
      $this->model->makesql($this->request->get('name'));
      echo '生成成功';exit;
    }
    //启用
    public function open(){
        $enname = $this->request->get('name');
        $m = $this->model->get(['enname' => $enname]);
        if($m['dir']){
            model('AuthRule')->where('name',$m['dir'].'/'.$enname.'/index')->update(['status' => 'normal']);
            model('AuthRule')->where('name',$m['dir'].'/'.$enname.'/add')->update(['status' => 'normal']);
            model('AuthRule')->where('name',$m['dir'])->update(['status' => 'normal']);
        }else{
            //没有目录
            model('AuthRule')->where('name',$enname)->update(['status' => 'normal']);
            model('AuthRule')->where('name',$enname.'/index')->update(['status' => 'normal']);
            model('AuthRule')->where('name',$enname.'/add')->update(['status' => 'normal']);
        }

    }
    //关闭
    public function close(){
        $enname = $this->request->get('name');
        $m = $this->model->get(['enname' => $enname]);
        if($m['dir']){
            model('AuthRule')->where('name',$m['dir'].'/'.$enname.'/index')->update(['status' => 'close']);
            model('AuthRule')->where('name',$m['dir'].'/'.$enname.'/add')->update(['status' => 'close']);
            model('AuthRule')->where('name',$m['dir'])->update(['status' => 'normal']);
        }else{
            //没有目录
            model('AuthRule')->where('name',$enname)->update(['status' => 'close']);
            model('AuthRule')->where('name',$enname.'/index')->update(['status' => 'close']);
            model('AuthRule')->where('name',$enname.'/add')->update(['status' => 'close']);
        }
    }
    //生成控制器
    public function makecontrollerphp(){
      $this->model->makecontrollerphp($this->request->get('name'));
      echo '生成成功';exit;
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
}
